/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "uninstaller.h"

Uninstaller::Uninstaller(QObject *parent) : QObject(parent)
{
    if (QFile::exists("/usr/lib/libkmre.so")) {
        this->libPath = "/usr/lib/libkmre.so";
    } else if (QFile::exists("/usr/lib/libkydroidrequest.so")) {
        this->libPath = "/usr/lib/libkydroidrequest.so";
    } else {
        qWarning() << "libPath not exists !!!";
    }

    QDBusConnection::systemBus().connect(QString("com.kylin.systemupgrade"),
                                         QString("/com/kylin/systemupgrade"),
                                         QString("com.kylin.systemupgrade.interface"),
                                         QString("PurgePackagesFinished"),
                                         this,
                                         SLOT(ordinaryAppUninstallComplete(bool, QString)));
}

void Uninstaller::uninstallApp(const QString &desktopFile)
{
    if (!m_uninstallAppList.empty()) {
        m_uninstallAppList.append(desktopFile);
        return;
    }
    m_uninstallAppList.append(desktopFile);
    qDebug() << __func__ << "后台开始卸载第一个应用" << m_uninstallAppList.value(0);
    doUninstallApp(m_uninstallAppList.value(0));
    m_uninstallAppDesktopname = m_uninstallAppList.value(0);
}
void Uninstaller::doUninstallApp(const QString &desktopFile)
{
    qDebug() << __FUNCTION__ << desktopFile;
    QSettings desktop(desktopFile, QSettings::IniFormat);
    QString desktopCmd = desktop.value("Desktop Entry/Exec").toString();
    if (desktopCmd.contains("/usr/bin/startapp")) {
        Q_EMIT appUninstalled(desktopFile);
        if (!uninstallAndroidApp(desktopCmd)) {
            Q_EMIT appUninstallFailed(desktopFile);
        }
        m_uninstallAppList.removeOne(desktopFile);
        if (!m_uninstallAppList.isEmpty()) {
            doUninstallApp(m_uninstallAppList.value(0));
            m_uninstallAppDesktopname = m_uninstallAppList.value(0);
        }
    } else {
        uninstallOrdinaryApp(desktopFile);
    }
}

bool Uninstaller::uninstallAndroidApp(const QString &desktopCmd)
{
    qDebug() << "kmre应用卸载";
    if (!QDBusConnection::sessionBus().isConnected()) {
        qWarning()<< "Cannot connect to the cn.kylinos.Kmre.Manager D-Bus sessionBus.";
        return false;
    }
    QStringList strList = desktopCmd.split(" ");
    QString packageName = strList.at(1);

    using namespace std;
    qDebug() << libPath;

    if (!QFile::exists(libPath)) {
        qWarning() << "libPath not exists !!!";
        return false;
    }
    void *module_handle;
    char *module_error;
    module_handle = dlopen(libPath.toStdString().c_str(), RTLD_LAZY);
    if (!module_handle) {
        qWarning() << "module_handle error !!!";
        dlclose(module_handle);
        return false;
    }

    int (*uninstall_app)(char *appname);
    uninstall_app = (int(*)(char *))dlsym(module_handle, "uninstall_app");
    if ((module_error = dlerror()) != NULL) {
        qWarning() << "module_error !!!";
        dlclose(module_handle);
        return false;
    }

    int nRes = uninstall_app(const_cast<char *>(packageName.toStdString().c_str()));
    if (nRes != 1) {
        qWarning() << "Android app uninstallation failed !!!";
        return false;
    }
    dlclose(module_handle);
    return true;
}

QString Uninstaller::getPkgNameByDesktop(const QString &desktopFile)
{
    std::string packName = "dpkg -S " + desktopFile.toStdString();
    char nameBuff[100] = "";
    FILE* fp = popen(packName.c_str(),"r");
    fgets(nameBuff, 100, fp);
    pclose(fp);
    std::string pkgInfo = nameBuff;
    if (pkgInfo.empty()) {
        qDebug()<<"---pkgInfo.isEmpty()---";
    }
    std::string pkg = std::string(pkgInfo.begin(), pkgInfo.begin() + pkgInfo.find(':'));
    QString pkgName = QString::fromStdString(pkg);
    qDebug() << "通过desktop获取包名" << pkgName;
    return pkgName;
}

void Uninstaller::uninstallOrdinaryApp(const QString &desktopFile)
{
    qDebug() << "apt应用卸载";
    if (!QDBusConnection::systemBus().isConnected()) {
        qWarning()<< "Cannot connect to the  com.kylin.systemupgrade D-Bus systemBus.";
        return;
    }
    //调用系统com.kylin.systemupgrade服务
    QDBusInterface aptRemoveFace("com.kylin.systemupgrade",
                         "/com/kylin/systemupgrade",
                         "com.kylin.systemupgrade.interface",
                         QDBusConnection::systemBus());
    if (aptRemoveFace.isValid()) {
        QString pkgName = getPkgNameByDesktop(desktopFile);
        qDebug()<< "卸载包名" << pkgName;
        QStringList purgeList;
        purgeList.append(pkgName);

        QString m_userName = qgetenv("USER");
        if (m_userName.isEmpty()) {
            m_userName = qgetenv("USERNAME");
        }
        QDBusPendingCall reply = aptRemoveFace.asyncCall("PurgePackages", purgeList, m_userName);

        QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
        QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(certificationResults(QDBusPendingCallWatcher*)));
    } else {
        qWarning()<<"aptRemoveFace 无法调用到PurgePackages方法";
    }
}

void Uninstaller::uninstallNextApp()
{
    m_uninstallAppList.removeOne(m_uninstallAppDesktopname);
    if (!m_uninstallAppList.isEmpty()) {
        m_uninstallAppDesktopname = m_uninstallAppList.value(0);
        doUninstallApp(m_uninstallAppDesktopname);
    }
}

void Uninstaller::certificationResults(QDBusPendingCallWatcher *call)
{
    QDBusPendingReply<int,QString> reply = *call;
    if (reply.reply().arguments().count() <= 0) {
        qWarning() << __func__ << "reply arguments is null";
        uninstallNextApp();
        return;
    }
    qdbus_cast<QDBusObjectPath>(reply.reply().arguments().first()).path();
    if (reply.isError()) {
        qWarning() << __func__ << reply.error().message();
        uninstallNextApp();
        return;
    }
    QList<QVariant> replyArguments = reply.reply().arguments();
    if (replyArguments[0].toInt() != 0) {
        uninstallNextApp();
        return;
    }

    Q_EMIT appUninstalled(m_uninstallAppDesktopname);
    call->deleteLater();
}

void Uninstaller::ordinaryAppUninstallComplete(bool uninstallResults, QString uninstallMessage)
{
    qDebug() << __func__ << uninstallResults << uninstallMessage;
    if (!uninstallResults && !uninstallMessage.contains("认证失败")) {
        Q_EMIT appUninstallFailed(m_uninstallAppDesktopname);
    }
    uninstallNextApp();
}
